package jumpingnotes.dao.hibernate;

import java.util.List;

import jumpingnotes.dao.ChapterDao;
import jumpingnotes.model.entity.Chapter;
import net.jf.lucene.analysis.mmseg.MMSegAnalyzer;

import org.apache.lucene.queryParser.MultiFieldQueryParser;
import org.apache.lucene.queryParser.ParseException;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.search.FullTextSession;
import org.hibernate.search.Search;
import org.springframework.orm.hibernate3.HibernateCallback;

public class ChapterHibernateDao extends GenericHibernateDao<Chapter> implements ChapterDao
{
	public ChapterHibernateDao()
	{
		super(Chapter.class);
	}

	@SuppressWarnings("unchecked")
	public List<Chapter> findChapterByBookId(final int bookId, final int firstResult, final int maxResults)
	{
		return (List<Chapter>) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session.createQuery("select distinct c from Chapter c where c.book.bookId=:bookId");
				query.setInteger("bookId", bookId);

				if (firstResult >= 0)
					query.setFirstResult(firstResult);
				if (maxResults > 0)
					query.setMaxResults(maxResults);

				return query.list();
			}
		});
	}

	@SuppressWarnings("unchecked")
	public Chapter findChapterByUuid(final String uuid)
	{
		return (Chapter) getHibernateTemplate().execute(new HibernateCallback()
		{
			public Object doInHibernate(Session session) throws HibernateException
			{
				Query query = session.createQuery("select distinct c from Chapter c where c.uuid=:uuid");
				query.setString("uuid", uuid);
				return query.uniqueResult();
			}
		});
	}

	@SuppressWarnings("unchecked")
	public void indexChapter()
	{
		Session session = getSession();
		FullTextSession fullTextSession = Search.createFullTextSession(session);

		List<Chapter> chapterList = session.createCriteria(Chapter.class).list();
		for (Chapter chapter : chapterList)
		{
			fullTextSession.index(chapter);
		}
	}

	@SuppressWarnings("unchecked")
	public List<Chapter> searchChapter(String keyword, int firstResult, int maxResults)
	{
		Session session = getSession();
		FullTextSession fullTextSession = Search.createFullTextSession(session);

		try
		{
			MultiFieldQueryParser parser = new MultiFieldQueryParser(new String[] { "name", "abstract_" },
					new MMSegAnalyzer());
			org.apache.lucene.search.Query query = parser.parse(keyword);
			Query hibQuery = fullTextSession.createFullTextQuery(query, Chapter.class);

			if (firstResult >= 0)
				hibQuery.setFirstResult(firstResult);
			if (maxResults > 0)
				hibQuery.setMaxResults(maxResults);

			List<Chapter> result = hibQuery.list();
			return result;
		}
		catch (ParseException e)
		{
			e.printStackTrace();
			return null;
		}
	}
}
